package com.moli.iov.base.remote.impl;

import com.moli.iov.base.enums.AuthorizedEnum;
import com.moli.iov.base.enums.UnauthLoginAuthEnum;
import com.moli.iov.base.enums.UnauthResultEnum;
import com.moli.iov.base.enums.UnauthStatusEnum;
import com.moli.iov.base.model.dto.req.VehicleBaseAuthReqDto;
import com.moli.iov.base.model.dto.req.VehicleTboxReqDto;
import com.moli.iov.base.model.dto.req.VehicleUnauthReqDto;
import com.moli.iov.base.model.dto.res.VehicleUnauthResDto;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleUnauth;
import com.moli.iov.base.remote.IVehicleBaseAuthRemoteService;
import com.moli.iov.base.remote.IVehicleBaseRemoteService;
import com.moli.iov.base.remote.IVehicleTboxRemoteService;
import com.moli.iov.base.remote.IVehicleUnauthRemoteService;
import com.moli.iov.base.service.IVehicleBaseService;
import com.moli.iov.base.service.IVehicleUnauthService;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 未授权登录管理
 * </p>
 *
 * @author zql
 * @since 2020/2/20 15:20
 */
@Slf4j
@Service(group = "${service.group}")
public class VehicleUnauthRemoteServiceImpl implements IVehicleUnauthRemoteService {

  @Autowired
  private IVehicleUnauthService vehicleUnauthService;

  @Autowired
  private IVehicleBaseService vehicleBaseService;

  @Autowired
  private IVehicleBaseRemoteService vehicleBaseRemoteService;

  @Autowired
  private IVehicleTboxRemoteService vehicleTboxRemoteService;

  @Autowired
  private IVehicleBaseAuthRemoteService vehicleBaseAuthRemoteService;

  /**
   * 增加未授权登录
   * @param vehicleUnauthReqDto
   * @return
   */
  @Override
  public RestResponse saveVehicleUnauth(VehicleUnauthReqDto vehicleUnauthReqDto) {
    log.info("增加未授权登录 入参：{}", vehicleUnauthReqDto);
    saveVehicleUnauthValid(vehicleUnauthReqDto);

    if(vehicleUnauthService.saveVehicleUnauth(assemblyVehicleUnauth(vehicleUnauthReqDto))){
      return RestResponse.success();
    }
    log.error("添加未授权登录记录失 数据：{}", vehicleUnauthReqDto);
    return RestResponse.failure("添加未授权登录记录失败");
  }

  /**
   * 添加登录异常记录校验
   * @param vehicleUnauthReqDto
   * @return
   */
  private void saveVehicleUnauthValid(VehicleUnauthReqDto vehicleUnauthReqDto){

    ValidationUtils.restResponseValidate(vehicleUnauthReqDto, VehicleUnauthReqDto.Save.class);

    VehicleUnauthReqDto rq = new VehicleUnauthReqDto();
    rq.setVin(vehicleUnauthReqDto.getVin());
    rq.setStatus(UnauthStatusEnum.UNPROCESSED.getFlag());
    List<VehicleUnauth> vehicleUnauths = vehicleUnauthService.listVehicleUnauth(rq);

    if(vehicleUnauths != null && !vehicleUnauths.isEmpty()){
      throw new BusinessException("存在未处理的记录");
    }

    log.info("添加登录异常记录校验 通过");
  }

  /**
   * 组装 VehicleUnauth
   * @param vehicleUnauthReqDto
   * @return
   */
  private VehicleUnauth assemblyVehicleUnauth(VehicleUnauthReqDto vehicleUnauthReqDto){

    VehicleUnauth vehicleUnauth = new VehicleUnauth();

    CommonUtils.copyProperties(vehicleUnauthReqDto, vehicleUnauth);
    vehicleUnauth.setStatus(UnauthStatusEnum.UNPROCESSED.getFlag());

    VehicleBase vehicleBase =
        vehicleBaseService.getVehicleBaseByVin(vehicleUnauth.getVin());
    if(vehicleBase != null){
      vehicleUnauth.setCompanyId(vehicleBase.getCompanyId());
      vehicleUnauth.setCompanyName(vehicleBase.getCompanyName());
    }

    return vehicleUnauth;
  }


  /**
   * 分页查询 未授权登录
   * @param vehicleUnauthReqDto
   * @return
   */
  @Override
  public RestResponse<PageExtend<VehicleUnauthResDto>> listPageVehicleUnauth(
      VehicleUnauthReqDto vehicleUnauthReqDto) {

    PageExtend<VehicleUnauth> pageExtend = vehicleUnauthService
        .listPageVehicleUnauth(vehicleUnauthReqDto);

    return RestResponse.success(convertPage(pageExtend));
  }


  /***
   * 转换分页数据
   * @param pageExtend
   * @return
   */
  private PageExtend<VehicleUnauthResDto> convertPage(PageExtend<VehicleUnauth> pageExtend ){

    PageExtend<VehicleUnauthResDto> page = new PageExtend<>();
    page.setRecords(convertList(pageExtend.getRecords()));
    page.setTotal(pageExtend.getTotal());
    page.setPageSize(pageExtend.getPageSize());
    page.setPageNumber(pageExtend.getPageNumber());

    return page;
  }

  /**
   * 转换List数据
    * @param vehicleUnauths
   * @return
   */
  private List<VehicleUnauthResDto> convertList(List<VehicleUnauth> vehicleUnauths){
    List<VehicleUnauthResDto> list = new ArrayList<>();
    vehicleUnauths.forEach(v -> {
      VehicleUnauthResDto vu = new VehicleUnauthResDto();
      CommonUtils.copyProperties(v, vu);
      vu.setStatusStr(UnauthStatusEnum.getMsg(v.getStatus()));
      vu.setResultStr(UnauthResultEnum.getMsg(v.getResult()));
      vu.setLoginAuthStr(UnauthLoginAuthEnum.getMsg(v.getLoginAuth()));
      list.add(vu);
    });

    return list;
  }

  /**
   * 处理
   * @param vehicleUnauthReqDto
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public RestResponse updateVehicleUnauthOfProcess(VehicleUnauthReqDto vehicleUnauthReqDto) {

    vehicleUnauthReqDto.setStatus(UnauthStatusEnum.PROCESSED.getFlag());
    updateVehicleUnauthOfProcessValid(vehicleUnauthReqDto);
    boolean ist = vehicleUnauthService.updateVehicleUnauthOfProcess(vehicleUnauthReqDto);

    if(!ist){
      return RestResponse.failure("处理失败");
    }

    VehicleUnauth vehicleUnauth = vehicleUnauthService.getById(vehicleUnauthReqDto.getUnauthId());

    if(vehicleUnauthReqDto.getResult() == UnauthResultEnum.PASS.getFlag()){
      //调用注册判断逻辑进行设备更换的计算，调整注册信息
      VehicleTboxReqDto vehicleTboxAddReqDto = new VehicleTboxReqDto();
      vehicleTboxAddReqDto.setVin(vehicleUnauth.getVin());
      vehicleTboxAddReqDto.setIccid(vehicleUnauth.getIccid());
      vehicleTboxAddReqDto.setDeviceId(vehicleUnauth.getDeviceId());
      vehicleTboxAddReqDto.setSysUserId(vehicleUnauthReqDto.getSysUserId());
      RestResponse restResponse = vehicleTboxRemoteService
          .gatewayRegisterVehicleTbox(vehicleTboxAddReqDto);
      if(restResponse == null){
        throw new BusinessException("设备更换失败");
      }else if(!restResponse.flag){
        throw new BusinessException(restResponse.getMessage());
      }
    }

    if(vehicleUnauthReqDto.getLoginAuth() == UnauthLoginAuthEnum.NOT_PASS.getFlag()){
      //拒绝登入的同时取消车辆的授权（直接在登入时拒绝，防止重复产生异常登入记录）; 处理失败抛出异常,回滚事物
      VehicleBaseAuthReqDto dto = new VehicleBaseAuthReqDto();
      dto.setVin(vehicleUnauth.getVin());
      dto.setLoginAuthStatus(AuthorizedEnum.UN_AUTHORIZED.getCode());
      dto.setSysUserId(vehicleUnauthReqDto.getSysUserId());
      dto.setSysRealName(vehicleUnauthReqDto.getSysRealName());
      dto.setSysCompanyId(vehicleUnauthReqDto.getSysCompanyId());
      dto.setSysCompanyName(vehicleUnauthReqDto.getSysCompanyName());
      RestResponse restResponse = vehicleBaseAuthRemoteService.updateVehicleBaseAuth(dto);
      if(restResponse == null){
        throw new BusinessException("取消车辆的授权失败");
      }else if(!restResponse.flag){
        throw new BusinessException(restResponse.getMessage());
      }
    }

    return RestResponse.success();
  }

  /**
   * 处理校验
   * @param vehicleUnauthReqDto
   */
  private void updateVehicleUnauthOfProcessValid(VehicleUnauthReqDto vehicleUnauthReqDto){

    ValidationUtils.restResponseValidate(vehicleUnauthReqDto, VehicleUnauthReqDto.Process.class);

    VehicleUnauth vehicleUnauth = vehicleUnauthService.getById(vehicleUnauthReqDto.getUnauthId());

    if(vehicleUnauth == null){
      throw new BusinessException("未授权记录id不存在");
    }

    if(vehicleUnauth.getStatus() == UnauthStatusEnum.PROCESSED.getFlag()){
      throw new BusinessException("当前记录已处理");
    }

    if(vehicleUnauthReqDto.getSysUserId() == null){
      throw new BusinessException("操作员id不能为空");
    }

    if(vehicleUnauthReqDto.getSysUserType() == UserTypeEnum.COMPANY.getFlag() &&
        !vehicleUnauthReqDto.getSysCompanyId().equals(vehicleUnauth.getCompanyId())){
      throw new BusinessException("只能处理能本企业未授权记录");
    }

    if(vehicleUnauthReqDto.getResult() == UnauthResultEnum.PASS.getFlag() &&
        vehicleUnauthReqDto.getLoginAuth() == UnauthLoginAuthEnum.NOT_PASS.getFlag()){
      throw new BusinessException("处理结果为同意登入，则登入授权只能为允许");
    }
  }
}
